import { FormatYMD } from "@/common/constants";
import { getLayoutProps } from "@/common/layout/getProps";
import { DeleteOutlined, DownloadOutlined, EditOutlined, PlusOutlined } from "@ant-design/icons";
import { PageContainer } from "@ant-design/pro-layout";
import {
  Button,
  Col,
  DatePicker, Descriptions, Divider,
  Form,
  Input,
  InputNumber, message, Modal,
  Row, Select, Space,
  Table,
  type TableColumnsType,
  type TableProps
} from "antd";
import Router from "next/router";
import dayjs from "dayjs";
import { useRouter } from "next/router";
import { useRouter as useNavigationRouter } from "next/navigation";
import { type FC, type HTMLAttributes, type Key, type PropsWithChildren, useEffect, useState } from "react";
import GlobalClasses from "@/styles/globalClasses.module.scss";
import styles from "./index.module.scss";
import { http } from "@/utils/request";
import { cloneDeep } from "lodash";

type TableDataType = {
  field1: string;
  field2: string;
  field3: string;
  field4: string;
  field5: string;
  field6: string;
  field7: string;
  field8: string;
  field9: string;
}

export const MajordomoAppraiseCU = () => {
  const nRouter = useNavigationRouter();
  const router = useRouter();
  const { query } = router;
  const { id, type } = query;
  const [form] = Form.useForm();
  // const [editForm] = Form.useForm();
  const [applicationData, setApplicationData] = useState<Partial<Record<string, any>>[]>([]);
  // const [open, setOpen] = useState<boolean>(false);

  const isAdd = !id && !type;
  const isEdit = !!id && !type;
  const isDetail = !!id && (type === "detail");


  const applicationColumns: TableColumnsType = [
    {
      align: "center",
      title: "序号",
      width: 60,
      key: "index",
      render: (_text: string, _record, index: number) => {
        return index + 1
      }
    },
    {
      align: "center",
      title: "姓名",
      dataIndex: "personName"
    },
    {
      align: "center",
      title: "职务",
      dataIndex: "personJob"
    },
    // {
    //   align: "center",
    //   title: "考评内容",
    //   dataIndex: "field2"
    // },
    // {
    //   align: "center",
    //   title: "工作质量(40%)",
    //   dataIndex: "field2"
    // },
    // {
    //   align: "center",
    //   title: "履职创新(15%)",
    //   dataIndex: "field2"
    // },
    // {
    //   align: "center",
    //   title: "团队协作(15%)",
    //   dataIndex: "field2"
    // },
    // {
    //   align: "center",
    //   title: "工作态度(15%)",
    //   dataIndex: "field2"
    // },
    // {
    //   align: "center",
    //   title: "服务满意度(15%)",
    //   dataIndex: "field2"
    // },
    // {
    //   align: "center",
    //   title: "多维度评测总分",
    //   dataIndex: "field2"
    // }
  ]
  
  const save = async() => {
    const values = await form.validateFields()
    values.evaluYear = dayjs(values.evaluYear).format('YYYY');
    const addFormData = {
      ...values,
      isSubmit:false,
      pmManyDimensionsEvaluItemQueryList:applicationData
    }
    if(isAdd){
      addSave(addFormData)
    }
    if(isEdit){
      editSave(addFormData)
    }
  }
  const submit = async() => {
    const values = await form.validateFields()
    values.evaluYear = dayjs(values.evaluYear).format('YYYY');
    const addFormData = {
      ...values,
      isSubmit:true,
      pmManyDimensionsEvaluItemQueryList:applicationData
    }
    if(isAdd){
      addSave(addFormData)
    }
    if(isEdit){
      editSave(addFormData)
    }
  }
  //新增接口
  const addSave = async(formData:object) =>{
    try {
      const res = await http.post({
        url:'/PmManyDimensionsEvalu/savePmManyDimensionsEvalu',
        data:formData,
      })
      if(res.code == 200){
        message.success('员工多维评测新增成功!');
        Router.push('/performanceAppraise/employeeMultiAppraise');
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  //编辑接口
  const editSave = async(formData:object) =>{
    try {
      const res = await http.post({
        url:'/PmManyDimensionsEvalu/updatePmManyDimensionsEvalu',
        data:{id,...formData,}
      })
      if(res.code == 200){
        message.success('员工多维评测修改成功!');
        Router.push('/performanceAppraise/employeeMultiAppraise');
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }

  // const handleOk = () => {
  //   message.success("edit success!")
  //   setTimeout(() => {
  //     setOpen(false);
  //   }, 500)
  // }

  // const handleCancel = () => {
  //   setOpen(false);
  // }
  //查询部门下面所有员工
  const getPersonByStaffId = async()=>{
    try {
      const res = await http.post({
        url:'/BaseUser/qryStaffBaseUserByOrgId',
        data:{bizUnitId:'0001101000000000182V'}
      })
      if(res.code == 200){
        const data = cloneDeep(res.rows);
        const arr = data.map(item=>({
          personId:item.staffNo,
          personName:item.name,
          personJob:item.positionName,
        }))
        setApplicationData(arr);
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  //根据id查询多维评测详情
  const getDetailById = async()=>{
    try {
      const res = await http.get({
        url:'/PmManyDimensionsEvalu/queryManyDimensionsEvaluDetail',
        params:{evaluId:id}
      })
      if(res.code == 200){
        const data = cloneDeep(res.data);
        data.evaluYear = dayjs().year(Number(data.evaluYear));
        form.setFieldsValue(data);
        form.setFieldsValue({
          date:data.applyTime,
        })
        const arr = data.pmManyDimensionsEvaluItemVos.map(item=>({
          id:item.id,
          manyDimensionsEvaluId:id,
          personId:item.personJob,
          personName:item.personName,
          personJob:item.personJob,
        }))
        setApplicationData(arr);
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  useEffect(() => {
    if (isEdit || isDetail) {
      getDetailById();
    } else {
      form.setFieldsValue({
        date:dayjs(new Date()).format('YYYY-MM-DD'),
        personName:'张三',
        deptName:'财务部门',
      })
      getPersonByStaffId();
    }
  }, []);

  return (
    <>
      <PageContainer header={{
        title: false
      }}>
        <div className={[styles.formCard, "mb-[20px]"].join(" ")}>
          <div
            className={[GlobalClasses.title, "title"].join(" ")}>{(isEdit && !isDetail) ? "编辑" : isAdd ? "新增" : ""}员工多维评测{isDetail ? "详情" : ""}</div>

          <Form form={form} layout={"vertical"} autoComplete="off">
            <Row>
              <Col span={6}>
                <Form.Item
                  label={"单据编号"}
                  name="code"
                >
                  <Input disabled></Input>
                </Form.Item>
                <Form.Item
                  label={"申请日期"}
                  name="date"
                >
                  <Input disabled></Input>
                </Form.Item>
              </Col>
              <Col span={6} offset={2}>
                <Form.Item
                  label={"申请人"}
                  name="personName"
                >
                  <Input disabled></Input>
                </Form.Item>
                <Form.Item
                  label={"考核年度"}
                  name="evaluYear"
                  rules={[{ required: true, message: '请选择考核年度!' }]}
                >
                  <DatePicker picker={'year'} disabled={isDetail}/>
                </Form.Item>
              </Col>
              <Col span={6} offset={2}>
                <Form.Item
                  label={"部门名称"}
                  name="deptName"
                >
                  <Input disabled></Input>
                </Form.Item>
              </Col>
            </Row>
          </Form>

          <Divider className={'mb-[20px] mt-0'} />

          {/* <Row justify={'end'}>
            {
              !(isAdd || isEdit) ?
                null :
                (
                  <Row justify={"end"} className={"mb-[20px]"}>
                    <Button type={"link"} icon={<DownloadOutlined/>}>下载模板</Button>
                    <Button type={"link"} icon={<DownloadOutlined/>}>导入</Button>
                  </Row>
                )
            }
          </Row> */}

          <Table
            className={'mb-[20px]'}
            rowKey={'personId'}
            dataSource={applicationData}
            columns={applicationColumns}
          ></Table>

          {
            !(isAdd || isEdit) ?
              <Row justify={'end'}>
                <Button onClick={() => {
                  nRouter.back();
                }}>返回</Button>
              </Row>
               :
              <Row justify={'end'}>
                <Space>
                  <Button onClick={()=>Router.push('/performanceAppraise/employeeMultiAppraise')}>取消</Button>
                  <Button onClick={save}>保存</Button>
                  <Button type={'primary'} onClick={submit}>提交</Button>
                </Space>
              </Row>
          }

          {/* <Modal
            open={open}
            title={`${JSON.stringify(currentEdit) === "{}" ? "新增" : "编辑"}总监绩效考核评价`}
            afterClose={() => editForm.resetFields()}
            onOk={handleOk}
            onCancel={handleCancel}
            okText={'提交'}
            cancelText={'取消'}
            footer={(_, { OkBtn, CancelBtn }) => (
              <>
                <CancelBtn />
                <OkBtn />
              </>
            )}
          >
            <Form form={editForm} colon={false} labelWrap initialValues={currentEdit} labelAlign={'left'} labelCol={{span: 6}}>
              <Form.Item
                label={'工作质量'}
                name={'field1'}
              >
                <Input placeholder={"请输入"}></Input>
              </Form.Item>
              <Form.Item
                label={'履职创新'}
                name={'field2'}
              >
                <Input placeholder={"请输入"}></Input>
              </Form.Item>
              <Form.Item
                label={'团队协作'}
                name={'field3'}
              >
                <Input placeholder={"请输入"}></Input>
              </Form.Item>
              <Form.Item
                label={'工作态度'}
                name={'field4'}
              >
                <Input placeholder={"请输入"}></Input>
              </Form.Item>
              <Form.Item
                label={'服务满意度'}
                name={'field5'}
              >
                <Input placeholder={"请输入"}></Input>
              </Form.Item>
            </Form>
          </Modal> */}
        </div>
      </PageContainer>
    </>
  )
}

export const getServerSideProps = getLayoutProps;
export default MajordomoAppraiseCU;
